<template>
  <el-dialog :visible="addVisible"  width="90%"  :title="dialogTitle" :before-close="closeDialog">
    <el-form :inline="true" :rules="rules" ref="form" :model="formData" label-width="180px" label-position="left" style="margin-left: 200px">
      <el-row class="row">
        <el-form-item label="应用范围 :" prop="application" >
          <el-radio v-model="formData.application" label="01"  @change="choseApplication">全部机构</el-radio>
          <el-radio v-model="formData.application" label="02"  @change="choseApplication">选定机构</el-radio>
        </el-form-item>
        <el-form-item >
        <el-col :span="20">
          <!-- <el-select v-model="formData.deptCode" filterable :disabled="depStatus"
                     placeholder="请选择部门" prop="deptCode">
            <el-option :label="option.deptName" :value="option.deptCode" v-for="(option, oi) in framedepartmentList"
                       :key="oi"></el-option>
          </el-select> -->
          <SelectTreeCom v-model="formData.jyjg" :isAll="false" :depStatus="depStatus"  ref="SelectTreeCom" ></SelectTreeCom>
        </el-col>
        </el-form-item>
      </el-row>
      <el-row  class="row">
        <el-form-item label="企业商品及服务编码:" prop="epsCode">
          <el-input v-model="formData.epsCode" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="企业商品及服务名称:" prop="epsName" >
          <el-input v-model="formData.epsName" placeholder="请输入"></el-input>
        </el-form-item>
      </el-row>
      <el-row  class="row">
        <el-form-item label="父级编码:" prop="parentCode" >
          <el-input v-model="formData.parentCode" placeholder="请输入" style="width: 200px">
            <el-button slot="append"  icon="el-icon-search" @click="queryFjbm"  >
            </el-button>
          </el-input>
          <!-- 跳转父级编码选择页面-->
          <chose-tax-dialog ref="choseTaxDialog" @getTaxClass="getTaxClass"></chose-tax-dialog>
        </el-form-item>
        <el-form-item label="商品及服务编码:"  prop="gstcmCode">
          <el-input :disabled="true" v-model="formData.gstcmCode" placeholder="请输入"></el-input>
        </el-form-item>
      </el-row>
      <el-row  class="row">
        <el-form-item label="商品及服务名称:"   prop="sphfwmc">
          <el-input :disabled="true" v-model="formData.sphfwmc" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="商品和服务分类简称:"  prop="sphfwfljc">
          <el-input :disabled="true" v-model="formData.sphfwfljc" placeholder="请输入"></el-input>
        </el-form-item>
      </el-row>
      <el-row  class="row">
        <el-form-item label="税率:" prop="zzssl">
          <el-select v-model="formData.zzssl" placeholder="请选择">
            <el-option
                v-for="item in zzsslList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠政策标识:"  prop="yhzcbs">
          <dict-select v-model="formData.yhzcbs" showCode :dict-code="DictCode.VMS_YHZCBS" @change="choseYhzcbs">
                       ></dict-select>
        </el-form-item>
      </el-row>
      <el-row  class="row">

        <el-form-item label="计量单位:" prop="jldw" >
<!--          <dict-select v-model="formData.jldw" showCode :dict-code="DictCode.VMS_106VAT"
                       @valueUpdated="handleValueUpdated" ></dict-select>-->
          <el-select v-model="formData.jldw"
          >
            <el-option
                v-for="option in jldwOptions"
                :key="option.lxxdm"
                :label="option.lxxmc"
                :value="option.lxxdm"
                :disabled="option.disabled"
            >
              <span style="float: left">{{ option.lxxmc }}</span>
              <span  style="float: right; color: #8492a6; font-size: 13px">{{ option.lxxdm }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计税方法:"  prop="jsff">
          <dict-select v-model="formData.jsff" showCode :dict-code="DictCode.VMS_JSFF"
                      ></dict-select>
        </el-form-item>
      </el-row>
      <el-row  class="row">
        <el-form-item label="征税项目:" prop="zsxm">
          <dict-select v-model="formData.zsxm" showCode :dict-code="DictCode.VMS_ZSXM"
                      ></dict-select>
        </el-form-item>
        <el-form-item label="启用日期:"  prop="qyrq">
          <el-date-picker type="date"  value-format="yyyy-MM-dd" placeholder="选择日期" v-model="formData.qyrq" style="width: 200px;"></el-date-picker>
        </el-form-item>
      </el-row>
      <el-row class="row">

        <el-form-item label="停用日期:" prop="tyrq">
          <el-date-picker type="date"  value-format="yyyy-MM-dd" placeholder="选择日期" v-model="formData.tyrq" style="width: 200px;"></el-date-picker>
        </el-form-item>
      </el-row>
      <el-row class="row">

      </el-row>
    </el-form>
    <el-row style="margin-top: 10px">
      <div class="centered-dialog">
        <el-button type="danger" size="mini" @click="closeDialog">取消</el-button>
        <el-button type="primary" size="mini" @click="confirmSubmit()" :loading="loading">
          保存
        </el-button>
      </div>
    </el-row>
  </el-dialog>
</template>

<script>
import DictSelect from "@/views/invoiceTemplate/components/DictSelect/DictSelect.vue";
import {DictCode} from "@/utils/DictConstant";
import {getFramedepartment} from "@/api/invoiceTemplate";
import SelectTreeCom from '@/components/selectTree/selectTreeCom.vue'

import {addServiceInfo, queryById, updateServiceInfo} from '@/api/serviceInformationManage.js'
import TaxClass from "@/views/taxClass/index.vue";
import ChoseTaxDialog from "./choseTaxDialog.vue";
import {getDefBIzdictByLxdm} from "@/api/system";
import fa from "element-ui/src/locale/lang/fa";

export default {
  computed: {
    DictCode() {
      return DictCode
    }
  },
  components: {ChoseTaxDialog, TaxClass, DictSelect, SelectTreeCom},
  props: {

  },
  data() {
    return {
      addVisible:false,//新增弹窗
      addDialogParam:'',
      dialogTitle:'新增产品信息',
      taxClassVisible: false,//税种弹窗
      loading: false,
      formData: {
        application: "01",
        //deptCode: "",
        epsCode: "",
        epsName: "",
        parentCode: "",
        gstcmCode: "",
        sphfwmc: "",
        sphfwfljc: "",
        zzssl: "",
        jldw: "",
        yhzcbs: "",
        jsff: "",
        zsxm: "",
        qyrq: "",
        tyrq: "",
        jyjg: "",
        kyslqyrq: '',
        kysltyrq: '',
      },
      rules: {
        application: [
            { required: true, message: '请选择', trigger: 'blur' }
            ],
        jyjg: [
            { required: true, message: '请选择部门', trigger: 'change' }
            ],
        epsCode: [
            { required: true, message: '请输入企业商品及服务编码', trigger: 'blur' },
            { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
            { pattern: /^[A-Za-z0-9]+$/, message: '只能输入数字或字母，请重新输入', trigger: 'blur' }
            ],
        epsName: [
            { required: true, message: '请输入企业商品及服务名称', trigger: 'blur' },
            { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
            ],
        parentCode: [
            { required: true, message: '请选择父级编码', trigger: 'blur' }

            ],
        gstcmCode: [
            { required: true, message: '请输入商品及服务编码', trigger: 'blur' }
            ],
        sphfwmc: [
            { required: true, message: '请输入商品及服务名称', trigger: 'blur' }
            ],
        sphfwfljc: [
            { required: true, message: '请输入商品和服务分类简称', trigger: 'blur' }
            ],
        zzssl: [
            { required: true, message: '请选择税率', trigger: 'blur' }
            ],
        jldw: [
            { required: true, message: '请选择计量单位', trigger: 'change' }
            ],
        jsff: [
            { required: true, message: '请选择计税方法', trigger: 'change' }
            ],
        zsxm: [
            { required: true, message: '请选择征税项目', trigger: 'change' }
            ],
        qyrq: [
            { required: true, message: '请选择启用日期', trigger: 'blur' }
            ],
        tyrq: [
            { required: true, message: '请选择停用日期', trigger: 'blur' }
            ],

      },
      framedepartmentList: [],
      getTaxClassData:null,
      options: [],
      depStatus: true,
      zzsslList: [],

      jldwoptions:[{
        lxxdm: "",
        lxxmc: "请选择"
      }],//原始计量单位数组，含全部计量单位
      jldwOptions:[], //页面展示数组，用于区分不动产和非不动产
      bdcOptions:[]

    };
  },
  mounted() {
    this.getFramedepartment();
    this.getJldwDictData();
    this.getBdcDictData();
  },
  methods: {
    closeDialog() {
      this.addVisible=false;
      this.$refs.SelectTreeCom.clearableFn();
      this.clearInfo()
    },
    //更新时初始化企业商品及服务信息
    async initInfo(id) {
      this.loading = true;
      this.id = id;
      if (this.id){
        let {data, code, message} = await queryById(
            id
        );
        if (code == 200) {
          this.loading = false;
          //这里将之前选择税收分类选择的税率预置到options中，方便用户选择非特定优惠标识时，有数据可以选择
          let sssl=data.options;
          let ssslList=[];
          if(sssl==null||sssl==''){

          }else {
            ssslList = sssl.split('、');
            if(ssslList!=null && ssslList.length>0){

              for (let i = 0; i < ssslList.length; i++) {
                let zzsslItem = {
                  label: ssslList[i],
                  value: ssslList[i],
                  selected: false,
                  disabled: false,

                }
                this.options.push(zzsslItem);
              }
            }
          }
          this.formData = data;
          this.handleValueUpdated('')
          this.extracted();

          //this.formData.zzssl=data.zzssl
        } else {
          this.loading = false;
          this.addVisible=false;
        }
      }
    },

    // 确认提交
    async confirmSubmit() {
       this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return false;
        }else {
          let b = this.isTyrqBeforeQyrq();
          if (b==='1') {
            this.$message({
              type: 'error',
              message: '启用日期范围是'+this.formData.kyslqyrq+'~'+this.formData.kysltyrq+"之间，请重新选择启用日期",

            })
            return false;
          }
          if (b==='2') {
            this.$message({
              type: 'error',
              message: '停用日期范围是'+this.formData.kyslqyrq+'~'+this.formData.kysltyrq+"之间，请重新选择停用日期",

            })
            return false;
          }
          if (b==='3') {
            this.$message({
              type: 'error',
              message: '停用日期不能大于启用日期',

            })
            return false;
          }
          if (this.addDialogParam==='add'){
            //this.formData.jyjg=this.formData.deptCode;
            let {data, code, message} = await addServiceInfo(this.formData)
            if (code == 200) {
              this.$message({
                type: 'success',
                message: '保存成功！',

              })
              this.closeDialog();
              this.$parent.getList();
              return false;
            } else {

              return false;
            }
          }else if (this.addDialogParam==='update'){
            let {data, code, message} = await updateServiceInfo(this.formData)
            if (code == 200) {
              this.$message({
                type: 'success',
                message: '更新成功！',

              })
              this.closeDialog();
              this.$parent.getList();
              return false;
            } else {
              this.$message({
                type: 'error',
                message: message,
              })
              return false;
            }
          }else {

          }
        }
       });
    },
    // 获取部门信息
    async getFramedepartment() {
      let {data, code, message} = await getFramedepartment({});
      if (code == 200) {
        this.framedepartmentList = data
      } else {
        this.$message({
          type: 'success',
          message: message,
        })
      }
    },
    //清空税率和预置税率，否则会有脏数据
    extracted2: function () {
      this.zzsslList = [];
      this.options = [];
    },
    /**
     * 清除表单数据
     */
    clearInfo() {
      this.formData = {
        application: '01',
        //deptCode: "",
        epsCode: "",
        epsName: "",
        parentCode: "",
        gstcmCode: "",
        sphfwmc: "",
        sphfwfljc: "",
        zzssl: "",
        jldw: "",
        yhzcbs: "",
        jsff: "",
        zsxm: "",
        qyrq: null,
        tyrq: null,
        jyjg: "",

      },
      this.depStatus=true
      this.extracted2();
    },
    /**
     * 查询服务编码
     */
    queryFjbm() {
      let params = {
        jyjg: this.formData.jyjg,
        application: this.formData.application,
      }
      this.$refs.choseTaxDialog.taxClassVisible=true;
      //打开子组件taxClassVisible
      this.$refs.choseTaxDialog.open( params);

    },
    /**
     * 获取子页面TaxClass回传到参数
     * @param data
     */
    getTaxClass(data) {
      this.getTaxClassData = data;

      this.formData.parentCode =data.fjbm;
      this.formData.sphfwfljc = data.sphfwfljc;//商品和服务分类简称
      this.formData.gstcmCode=data.sphfwssflhbbm;//商品及服务编码&&商品和服务税收分类合并编码  ---具备唯一性
      this.formData.sphfwmc=data.sphfwmc;//商品和服务名称
      this.formData.kysltyrq=data.tyrq;//可用税率停用期限
      this.formData.kyslqyrq=data.qyrq;//可用税率启用期限
      //this.handleValueUpdated( this.formData.gstcmCode)
      this.handleValueUpdated("")
      //拆分税率。并且将拆分后的税率，以select组合的形式，放到页面上formData.zzssl
      // 如果优惠政策标识不为空，则不重新赋值税率

      //判断是否有优惠标识选择，并且在可回显范围
      var yhbsFlag= this.formData.yhzcbs != '01' && this.formData.yhzcbs != '03'
              && this.formData.yhzcbs != '04'&& this.formData.yhzcbs != '08'
              && this.formData.yhzcbs != '09' && this.formData.yhzcbs != '10'
      if(yhbsFlag){
          this.zzsslList = [];
          this.formData.zzssl= ''
          let zzssl = data.zzssl;
          if(zzssl==null||zzssl==''){
            this.$message({
              type: 'error',
              message: '税率为空，请重新选择父级编码',
            })
            return false;
          }else {
            zzssl = zzssl.split('、');
            if(zzssl.length==0){
              this.$message({
                type: 'error',
                message: '税率格式有误，请重新选择父级编码',
              })
              return false;
            }
            //let zzsslList = [];
            for (let i = 0; i < zzssl.length; i++) {
              let zzsslItem = {
                label: zzssl[i],
                value: zzssl[i],
                selected: false,
                disabled: false,

              }
              this.zzsslList.push(zzsslItem);
            }

              //为true，保存父级编码过来的数据，用于改变优惠码时，可以选择,options用来临时保存选择的父级编码的税率
              this.options=this.zzsslList;
            }
          }

    },
    choseApplication() {
      let ap= this.formData.application;
      if (ap==='02'){
        //禁用‘请选择部门’ 选择框
        this.depStatus=false
      }else {
        //全部机构，清空选择机构，并置灰按钮
        this.formData.jyjg='';
        this.$refs.SelectTreeCom.clearableFn();
        this.depStatus=true
      }
    },
    isTyrqBeforeQyrq() {


      //启用日期不能在可用税率启用日期之前，停用日期不能再可用税率停用日期之后
      if(new Date(this.formData.qyrq)<new Date(this.formData.kyslqyrq) || new Date(this.formData.qyrq)>new Date(this.formData.kysltyrq)){
        return '1';
      }

      if(new Date(this.formData.tyrq)>new Date(this.formData.kysltyrq) || new Date(this.formData.tyrq)<new Date(this.formData.kyslqyrq)){
        return '2';
      }
      if (this.formData.qyrq && this.formData.tyrq) {
        if(new Date(this.formData.tyrq) < new Date(this.formData.qyrq)) {
          return '3';
        }
      }
      return false;
    },
    extracted(){
      //在之前选择父级编码的时候，不进行判断，option和zzsslList都是有值的，页面用的是opiton,zzsl保存页面选择的税率，这里进行改变，
      // 如果是03这些的值，将页面的option进行替换，如果不是03这些，则使用之前的zzsslList
      //为true时，按照父级编码的税率，进行赋值，false时，按照之前选中的税率，进行赋值
      var yhbsFlag= this.formData.yhzcbs != '01' && this.formData.yhzcbs != '03'
          && this.formData.yhzcbs != '04'&& this.formData.yhzcbs != '08'
          && this.formData.yhzcbs != '09' && this.formData.yhzcbs != '10'
      let zzsslItem1 = {
        label: '3%',
        value: '3%',
        selected: false,
        disabled: false,

      }
      let zzsslItem2 = {
        label: '5%',
        value: '5%',
        selected: false,
        disabled: false,

      }
      let zzsslItem3 = {
        label: '1.5%',
        value: '1.5%',
        selected: false,
        disabled: false,

      }
      if (this.formData.yhzcbs == '01') {
        //简易征收-->票面税率3%；5% 下拉选择
        this.zzsslList.push(zzsslItem1);
        this.zzsslList.push(zzsslItem2);
      } else

          //不征税 -->不征税 04
      if (this.formData.yhzcbs == '04') {
        let zzsslItem4 = {
          label: '不征税',
          value: '不征税',
          selected: true,
          disabled: false,

        }
        this.zzsslList.push(zzsslItem4);
      }
      //免税-->免税 03 自动选择免税
      if (this.formData.yhzcbs == '03') {
        let zzsslItem5 = {
          label: '免税',
          value: '免税',
          selected: true,
          disabled: false,

        }
        this.zzsslList.push(zzsslItem5);
      }
      //按3%简易征收 -->3% 08
      if (this.formData.yhzcbs == '08') {
        zzsslItem1.selected = true;
        this.zzsslList.push(zzsslItem1);
      } else
          //按5%简易征收-->5% 09
      if (this.formData.yhzcbs == '09') {
        zzsslItem2.selected = true;
        this.zzsslList.push(zzsslItem2);
      } else
          //按5%简易征收减按1.5%计征 1.5% 10
      if (this.formData.yhzcbs == '10') {
        zzsslItem3.selected = true;
        this.zzsslList.push(zzsslItem3);
      } else
          //如果上述特定元素，清空税率，否则，不清空
          //其他正常从父类编码正常取值
      if (yhbsFlag) {

        this.zzsslList = this.options;
      }
    },
    choseYhzcbs() {

      this.formData.zzssl= '';
      this.zzsslList=[];
      this.extracted();
    },
    /**
     * 判断是否是不动产的父类编码，
     * 只有在更新数据 即 initInfo 方法
     * 或者选择父类编码后才会调用 即 getTaxClass方法
     * 其他时间不调用，单位默认全部不置灰
     * @param value  ===>formData.gstcmCode 来自于税收分类编码
     */
    handleValueUpdated(value){
      //判断formData.gstcmCode 商品服务编码。如果是不动产，执行此方法，置灰非不动产的单位，否则置灰不动产的专属计量单位
      //这个方法在选择父类编码，或者更新条目初始化时进行调用
      // 复制 jldwoptions 数组，以确保原始选项不会改变
      let bdcFlag =false;
      this.jldwOptions = this.jldwoptions.map(option => ({ ...option }));
      this.bdcOptions.forEach(option => {
        if (option.lxxmc === value) {
          bdcFlag = true;

        }
      });
      if(bdcFlag){
        //这里先这样写，后续根据formData.gstcmCode 修改；而gstcmCode是根据乐企接口中税收分类编码里的
        // “商品及服务的税收分类合并编码“决定的

        // 根据 value 的值进行设置选项的 disabled 属性
        this.jldwOptions.forEach(option => {
          if (option.lxxdm > 100) {
            option.disabled = false;
          } else {
            option.disabled = true;
          }
        });
      }else{
        // 根据 value 的值进行设置选项的 disabled 属性
        this.jldwOptions.forEach(option => {
          if (option.lxxdm > 100) {
            option.disabled = true;
          } else {
            option.disabled = false;
          }
        });
      }

    },
    /**
     * 获取计量单位的数组，在index刷新的时候就已经加载好了
     * @returns {Promise<void>}
     */
    async getJldwDictData() {
      let params = {
        lxdm: DictCode.VMS_106VAT
      }
      let {data, code, message} = await getDefBIzdictByLxdm(params);
      if (code == 200) {
        this.jldwoptions = data;  // 更新jldwoptions数组
        // 复制 jldwoptions 数组，以确保原始选项不会改变
        this.jldwOptions = [...this.jldwoptions];
      } else {

      }
    },
    async getBdcDictData() {
      let params = {
        lxdm: 'VAT-BDC-001'
      }
      let {data, code, message} = await getDefBIzdictByLxdm(params);
      if (code == 200) {
        this.bdcOptions = data;  // 更新jldwoptions数组
      } else {

      }
    }
  },
};
</script>

<style  lang = "scss" scoped>
@import '@/style/variables.scss';
.centered-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-form-item{
  margin-left: 30px;
  .el-input{
    width: 200px;
  }
}

</style>